package icu.xblogs.report.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author Frank KONG
 * @version 1.0
 * @date 2020/8/4 20:18
 */

/**
 * 用于封装对cookie的读写操作
 */
public class CookieUtil {

    private static final int DEFAULT_EXPIRY = 1296000; //默认15天

    /**
     * 读取Cookie
     * @param request
     * @param names 需要读出来的cookie
     * @return
     */
    public static HashMap<String, String> getCookie(HttpServletRequest request, String... names){
        HashMap<String, String> hashMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();

        if(cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                for (String name : names) {
                    if (name.equals(cookie.getName())) {
                        hashMap.put(cookie.getName(), cookie.getValue());
                    }
                }
            }
        }

        return hashMap;
    }

    /**
     * 用户上线,增加Cookie
     * @param response
     * @param key_value key_value一一对应的hashMap
     * @param expiry
     */
    public static void addCookie(HttpServletResponse response, HashMap<String, String> key_value, int expiry){
        if(key_value.isEmpty()) return;
        for (String name : key_value.keySet()) {
            //System.out.println(name);
            Cookie cookie = new Cookie(name, key_value.get(name));
            cookie.setPath("/");
            cookie.setMaxAge(expiry);
            response.addCookie(cookie);
        }
    }

    public static void addCookie(HttpServletResponse response, HashMap<String, String> key_value){
        addCookie(response, key_value, DEFAULT_EXPIRY);
    }

    /**
     * 用户退出,删除对应Cookie
     * @param request
     * @param response
     * @param names
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String... names){
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length != 0){
            for (Cookie cookie : cookies) {
                for (String name : names) {
                    if (name.equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
            }
        }
    }

}
